const fs = require('fs')
const path = require('path')
const mammoth = require('mammoth')
const xlsx = require('xlsx')
const {readFileContent} = require('../misc/util')

const handlers = [{
  test: /\.docx$/i,
  async handler(filename, {output}) {
    const {value} = await mammoth.convertToHtml({path: filename})
    fs.writeFileSync(output, value)
    return {ext: '.html', mime: 'text/html'}
  }
}, {
  test: /\.pdf$/i,
  handler(filename, {output}) {
    const content = fs.readFileSync(filename)
    fs.writeFileSync(output, content)
    return {ext: '.pdf', mime: 'application/pdf'}
  }
}, {
  test: /\.xlsx?$/i,
  async handler(filename, {output}) {
    const tpl = await readFileContent(path.join(__dirname, 'tpls/excel.html'))
    const names = []
    const sheets = []
    const workbook = xlsx.readFile(filename)
    let i = 0
    for (const sheetName of workbook.SheetNames) {
      const active = i ? '' : ' active'
      const link = `<a href="javascript:" class="nav-link${active}">${sheetName}</a>`
      names.push(`<li data-sheet="${i}" class="nav-item table-sheet--name">${link}</li>`)
      const sheet = workbook.Sheets[sheetName]
      let table
      if (sheet['!ref']) {
        const html = xlsx.utils.sheet_to_html(sheet)
        // 取出中间的 table 部分
        table = '<table class="table table-bordered table-hover table-sm"' + html.substring(
          '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body><table'.length,
          html.length - '</body></html>'.length
        )
      } else {
        //  <td> </td> 中间添加一个空格，以使界面能正常显示
        const emptyRows = []
        for (let j = 0; j < 16; j++) {
          emptyRows.push('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>')
        }
        table = `<table class="table table-bordered table-sm">${emptyRows.join('')}</table>`
      }
      sheets.push(`<div data-sheet="${i}" class="table-responsive table-content--sheet${active}">${table}</div>`)
      i++
    }
    fs.writeFileSync(output, tpl.replace('${names}', names.join('')).replace('${sheets}', sheets.join('')))
    return {ext: '.html', mime: 'text/html'}
  }
}]

module.exports = handlers
